package com.lengyu.vxminiprogram.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lengyu.vxminiprogram.common.AuthUtil;
import com.lengyu.vxminiprogram.common.BasePageParamDto;
import com.lengyu.vxminiprogram.common.CommonUtils;
import com.lengyu.vxminiprogram.common.HttpResultDto;
import com.lengyu.vxminiprogram.convert.ISecretRealmConverter;
import com.lengyu.vxminiprogram.dto.SecretRealmDto;
import com.lengyu.vxminiprogram.dto.WorkOrderDto;
import com.lengyu.vxminiprogram.dto.WorkOrderRequestDto;
import com.lengyu.vxminiprogram.entity.SecretRealm;
import com.lengyu.vxminiprogram.entity.WorkOrderProcView;
import com.lengyu.vxminiprogram.entity.WorkOrderUserView;
import com.lengyu.vxminiprogram.entity.WorkOrderView;
import com.lengyu.vxminiprogram.security.rest.dto.JwtUser;
import com.lengyu.vxminiprogram.service.ISecretRealmService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuyu
 * @since 2024-12-10
 */
@RestController
@RequestMapping("/secret-realm")
public class SecretRealmController {
    private final static Logger logger = LoggerFactory.getLogger(SecretRealmController.class);
    @Autowired
    ISecretRealmService secretRealmService;

    @Autowired
    ISecretRealmConverter secretRealmConverter;

    private static Map<String,List<SecretRealmDto>> uploadMap = new HashMap<>();

    @PostMapping(value="/save")
    public HttpResultDto<String> save(@RequestBody SecretRealm secretRealm){
        secretRealmService.saveOrUpdate(secretRealm);
        return HttpResultDto.success();
    }

    /**
     * 批量导入文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload-file")
    public HttpResultDto<List<SecretRealm>> uploadFile(@RequestPart("file") MultipartFile file){
        JwtUser currentUser = AuthUtil.getCurrentJwtUser();
        if(currentUser == null){
            return HttpResultDto.failed("无权限");
        }
        //判断文件是否为空
        if(file.isEmpty()){
            return HttpResultDto.failed("文件不能为空");
        }
        try {
            List<SecretRealmDto> secretRealmList = new ArrayList<>();
            // 使用BufferedReader逐行读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {

                secretRealmService.transferDataLine(line,secretRealmList);
            }
            reader.close();
            logger.info("战斗日志读取完成：" + JSONObject.toJSONString(secretRealmList));
            List<SecretRealm> secretRealmEntityList = secretRealmConverter.listDtoToEntity(secretRealmList);
            secretRealmService.saveBatch(secretRealmEntityList);
            return HttpResultDto.success();
        } catch (Exception e) {
            return HttpResultDto.failed(e.getMessage());
        }
    }
    /**
     * 批量导入文件上传
     * @param
     * @return
     */
    @PostMapping("/upload-files-part")
    public HttpResultDto<List<SecretRealm>> uploadFilePart(HttpServletRequest request,
                                                            @RequestParam(name = "index") int index,
                                                           @RequestParam(name = "totalIndex") int totalIndex,
                                                           @RequestParam(name = "fileName") String fileName) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        logger.info("参数:"+JSONObject.toJSONString(request.getQueryString()));
        logger.info("参数:"+index);
        logger.info("参数:"+totalIndex);
        logger.info("参数:"+fileName);

        while ((line = reader.readLine()) != null) {
            // 处理读取到的每一行
            if(!uploadMap.containsKey(fileName)){
                List<SecretRealmDto> secretRealmList = new ArrayList<>();
                uploadMap.put(fileName, secretRealmList);
            }
            secretRealmService.transferDataLine(line,uploadMap.get(fileName));
        }

        inputStream.close();
        if(index+1 == totalIndex){
            List<SecretRealm> realmList = secretRealmConverter.listDtoToEntity(uploadMap.get(fileName));
            secretRealmService.saveBatch(realmList);
            uploadMap.remove(fileName);
        }
        return HttpResultDto.success();
    }



    @PostMapping(value="/page")
    public HttpResultDto<Page<SecretRealmDto>> page(@RequestBody BasePageParamDto pageParamDto){
        QueryWrapper queryWrapper = new QueryWrapper();
        if(pageParamDto.getParamMapObj() != null){
            for(String key:pageParamDto.getParamMapObj().keySet()){
                if(StringUtils.isNotBlank(String.valueOf(pageParamDto.getParamMapObj().get(key)))){

                        queryWrapper.like(key,pageParamDto.getParamMapObj().get(key));


                }
            }
        }

        logger.info(JSONObject.toJSONString(queryWrapper));
        queryWrapper.orderByDesc("realm_time");
        Page<SecretRealm> entityPage = secretRealmService.page(new Page<>(pageParamDto.getPageIndex(), pageParamDto.getPageSize()),queryWrapper);
        Page<SecretRealmDto> dtoPage = secretRealmConverter.pageEntityToDto(entityPage);
        if(dtoPage.getRecords() != null && dtoPage.getRecords().size() > 0){
        }
        return HttpResultDto.success(dtoPage);

    }

    @GetMapping(value="/detail")
    public HttpResultDto<SecretRealmDto> detail(String id){
        SecretRealm secretRealm = secretRealmService.getById(id);
        logger.info(JSONObject.toJSONString(secretRealm));
        SecretRealmDto secretRealmDto = secretRealmConverter.entityToDto(secretRealm);

        return HttpResultDto.success(secretRealmDto);
    }
}
